package com.example.servicezuul.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhang.test.common.util.Constants;
import com.zhang.test.common.util.TokenUtil;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

@Component
public class MyZuulFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(MyZuulFilter.class);


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        String accessToken = request.getParameter("token");
        if (accessToken == null) {
            Cookie cookie = Arrays.stream(request.getCookies()).filter(x -> x.getName().equals(Constants.X_TOKEN)).findFirst().orElse(null);
            try {
                if (cookie == null) {
                    log.warn("token is empty");
                    ctx.setSendZuulResponse(false);
                    ctx.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
                    ctx.getResponse().getWriter().write("token is empty");
                } else {
                    accessToken = cookie.getValue();
                    Map resultMap = TokenUtil.getInstance().valid(accessToken);
                    log.info("{}", cookie.getValue());
                    log.info("resultMap={}", resultMap);
                    ctx.setSendZuulResponse(true);
                    ctx.setResponseStatusCode(HttpStatus.SC_OK);

                    return true;
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

            return null;
        }
        log.info("ok");
        return null;
    }


}
